<?php
defined('BASEPATH') or exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{

    public $user, $uid,$userInfo;

    public function __construct()
    {
        parent::__construct();

        $this->load->helper('url');
        $newuri = strtolower(uri_string());
        $this->config->load('route', true);
        // 验证token并把token
        $token = get_cookie('myt_user');
        $this->load->library('encrypt');
        $user_cookie = explode("-", $this->encrypt->decode($token));
//        echo $token;
        //dd($user_cookie);
        // 验证token是否已经过期
        if (($user_cookie[2] - time()) < 0) { // 暂时设置成两个小时过期
            if($user_cookie[3] == 1){ // 正常用户
                if($user_cookie[1] != 1){ // 如果不是普通用户
                    $user = (array)$this->db->where('id',$user_cookie['0'])->get('user')->row_array();
                    if(strtotime($user['level_expire_at']) > time()){ // 用户续费了，重写cookie
                        $token = $this->encrypt->encode($user['id']."-".$user['level']."-".strtotime($user['level_expire_at'])."-".$user_cookie[3]); // id:用户名:失效时间:权限json
                        setcookie("myt_user", $token, 99*365*3600*24,'/');
                        $this->userInfo = [
                            'user_id' => $user_cookie[0],
                            'perm' => json_decode($user_cookie[4], true)
                        ];
                    }else{ // 删除token，重新登录
                        setcookie('myt_user','',time()-1,'/');
                        //redirect('/');
                    }
                }
            }else{
                // 写入退出日志
                $this->load->model(array('user/ipuser_log_model'=>'ipuser_log'));
                $this->ipuser_log->quit($user_cookie[0],getip(),$user_cookie[5],$user_cookie[6]);
                setcookie('myt_user','',time()-1,'/');
            }

        }else{ // cookie尚未过期，把cookie数据拿出来作为公共用户信息
            $this->userInfo = [
                'user_id' => $user_cookie[0],
                'key' => $user_cookie[5],
                'perm' => json_decode($user_cookie[4], true),
                'time' => $user_cookie[6]
            ];
            if($user_cookie[3] == 2){ // IP段用户，每次都要延长30分钟
                $this->load->model(array('user/ipuser_log_model'=>'ipuser_log'));
                $this->ipuser_log->reset($user_cookie[0],getip(),$user_cookie[5],$user_cookie[6]);
            }


        }
        //dd($this->userInfo);
        //判断登录
        if (!$this->userInfo) {
            echo '<script>location.href="' . base_url() . 'login"</script>';
            exit;
        }
        $whitelist = $this->config->item('whitelist', 'route');
        $routePerMap = $this->config->item('routePerMap', 'route');
       if (!in_array($newuri, $whitelist) && !preg_match('/^users/is',$newuri)) {

            //判断权限
            if (!in_array($routePerMap[$newuri],  $this->userInfo['perm'])) {
                echo '<script>alert("您没有权限");javascript:history.go(-1);</script>';
                exit;
            }
        }
        // 获取导航地址
        $navs = $this->db->where('show',1)->order_by('sort asc,id asc')->get('system_nav')->result_array();
        $top_bar = array_values(getChild($navs));
        $data = array(
            'top_bar' => array_values($top_bar),
			'imgurl' => '/v2static',
        );
        $data['user_id'] = $this->userInfo['user_id'] ? $this->userInfo['user_id'] : 0;
        $data['user_info'] = $this->userInfo;
        $this->load->vars($data);
    }

    /**
     * 获取表字段以及注释
     * @param $table
     * @return array
     */
    public function table_info($table)
    {
        $sql = "SELECT column_name , COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" . $this->db->dbprefix . $table . "' AND table_schema = '" . $this->db->database . "'";
        $res = $this->db->query($sql)->result_array();
        $res = array_combine(array_column($res, 'column_name'), array_column($res, 'COLUMN_COMMENT'));
        return $res;
    }

    /**
     * 指定股票天的趋势图
     */
    public function stock_day($table, $stock_name = "", $field = "date,*", $wfield = 'stock_name', $order = "date")
    {
        if ($stock_name != '') {
            $this->db->where($wfield, $stock_name);
        }
        $res = $this->db->select($field)->order_by($order, 'asc')->get($table)->result_array();
        return $res;
    }

    /**
     * 查看每个股市的 更多链接
     * @param $stock
     */
    function stock_posi($stock){
        $posi = $this->db->where('id',$stock)->get('chart_posi')->row_array();
        $return = '';
        if(!empty($posi) && !empty($posi['datas'])){
            $return = json_decode($posi['datas'],true);
            $return = implode(",",array_values($return));
        }
        return $return;
    }

    public function make_page($node,$total_nums){
        //echo $total_nums;exit;
        $this->load->library('pagination');
        $config['base_url'] = base_url().$node;
        $config['total_rows'] = $total_nums;
        $config['per_page'] = 20;
        $config['uri_segment'] = 3;
        $config['page_query_string'] = true;
        $config['cur_tag_open'] = '<span>';
        $config['cur_tag_close'] = '</span>';
        $config['first_link'] = '<<';
        $config['last_link'] = '>>';
//        $config['num_tag_open'] = '<a>';
//        $config['num_tag_close'] = '</a>';

//        $config['first_tag_open'] = '<li class="paginate_button previous">';
//        $config['first_tag_close'] = '</li>';
//        $config['last_tag_open'] = '<li class="paginate_button next">';
//        $config['last_tag_close'] = '</li>';
//        $config['next_tag_open'] = '<li class="paginate_button">';
//        $config['next_tag_close'] = '</li>';
//        $config['prev_tag_open'] = '<li class="paginate_button">';
//        $config['prev_tag_close'] = '</li>';

        $this->pagination->initialize($config);
        return $this->pagination->create_links();
    }
}
